import React, {
  useState,
  createContext,
  useContext,
  CSSProperties
} from 'react';
import { Modal, Button, ModalProps } from '@arco-design/web-react';

type CustomeModalProps = {
  showFooter?: boolean;
  children?: React.ReactNode;
} & ModalProps;

type contextProps = {
  visible?: boolean;
  showModal?: (model: CustomeModalProps) => void;
  hideModal?: () => void;
  modalProps?: CustomeModalProps;
  closable?: boolean;
  style?: CSSProperties;
  footer?: React.ReactNode;
  onOk?: () => void;
  title?: React.ReactNode | string;
  showFooter?: boolean;
  children?: React.ReactNode;
};

const initState: contextProps = {
  closable: false,
  showFooter: true
};

const ModalContext = createContext(initState);

export const ModalServiceProvider = ({
  children
}: {
  children: React.ReactNode;
}) => {
  const [visible, setVisible] = useState(false);
  const [modalProps, setModalProps] = useState<contextProps>({
    closable: false,
    showFooter: true
  });

  const showModal = (props) => {
    setModalProps((pre) => {
      return {
        ...pre,
        ...props
      };
    });
    setVisible(true);
  };

  const hideModal = () => {
    setVisible(false);
  };

  return (
    <ModalContext.Provider
      value={{ visible, showModal, hideModal, modalProps }}
    >
      {children}
      <Modal
        title={modalProps.title}
        visible={visible}
        onCancel={hideModal}
        onOk={modalProps.onOk}
        closable={modalProps.closable}
        style={modalProps.style}
        footer={
          modalProps.showFooter
            ? modalProps.footer || [
                <Button key="cancel" onClick={hideModal}>
                  取消
                </Button>,
                modalProps.onOk ? (
                  <Button key="ok" type="primary" onClick={modalProps.onOk}>
                    确定
                  </Button>
                ) : null
              ]
            : null
        }
      >
        {modalProps.children}
      </Modal>
    </ModalContext.Provider>
  );
};

// 自定义 Hook，用于在组件中使用 Modal Context
export const useModal = () => useContext(ModalContext);
